package com.example.miniostudy.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.miniostudy.utils.MinioUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/file/")
public class FileController {
    @Autowired
    private MinioUtils minioUtils;

    /**
     * 上传文件
     */
    @PostMapping("upload")
    public JSONObject upload(@RequestParam(name = "file",required = false) MultipartFile file){
        JSONObject res = new JSONObject();
        try {
            res = minioUtils.uploadFile(file,"mybucket");
            res.put("code", 1);
            res.put("msg", "OK");
        } catch (Exception e){
            e.printStackTrace();
            res.put("code",0);
            res.put("msg","上传失败" + e.getMessage());
        }
        System.out.println(res.toString());

        return res;
    }

    /**
     * 删除文件
     * @param fileName
     * @throws Exception
     */
    @RequestMapping("delete/{fileName}")
    public JSONObject delete(@PathVariable("fileName") String fileName) throws Exception{
        minioUtils.removeObject("mybucket", fileName);

        JSONObject res = new JSONObject();
        res.put("code", 1);
        res.put("msg", "OK");
        System.out.println("删除成功");

        return res;
    }

    /**
     * 下载文件
     */
    @RequestMapping("download")
    public void download(@RequestParam(name = "fileName",required = false) String fileName, HttpServletResponse response) {
        try {
            response.getOutputStream();
            InputStream is = minioUtils.getObject("mybucket", fileName);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

            OutputStream out = response.getOutputStream();
            byte[] b = new byte[1024];  //创建数据缓冲区
            int length = 0;
            while((length = is.read(b)) > 0 ) {
                out.write(b,0,length);
            }
            out.flush();
            out.close();
            is.close();
            System.out.println("下载成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
